package com.lfs.adapter.base.pdd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.doudian.open.gson.Gson;
import com.lfs.adapter.dto.PddDataUploadImageDto;
import com.lfs.adapter.dto.PddGoodsPropertiesDto;
import com.lfs.adapter.dto.PddProductPropertyDto;
import com.lfs.adapter.service.PlatformManagerService;
import com.lfs.adapter.vo.PddGoodsGoodsCatsVO;
import com.lfs.base.exception.BusinessException;
import com.pdd.pop.sdk.http.api.file.request.PddGoodsFilespaceImageUploadRequest;
import com.pdd.pop.sdk.http.api.file.request.PddGoodsImgUploadRequest;
import com.pdd.pop.sdk.http.api.file.response.PddGoodsFilespaceImageUploadResponse;
import com.pdd.pop.sdk.http.api.file.response.PddGoodsImgUploadResponse;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.CarouselVideoItem;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.GoodsPropertiesItem;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.SkuListItem;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.SkuListItemSkuPropertiesItem;
import com.lfs.common.enums.EnumShopType;
import com.lfs.interfaces.dao.PlatformDao;
import com.lfs.interfaces.dto.LogisticsTemplateDto;
import com.lfs.interfaces.dto.TokenCreateDto;
import com.lfs.interfaces.model.PlatformEntity;
import com.lfs.interfaces.model.vo.LogisticsTemplateResultVo;
import com.lfs.interfaces.model.vo.LogisticsTemplateVo;
import com.lfs.interfaces.model.vo.MallInfoVo;
import com.lfs.interfaces.model.vo.TokenCreateVo;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.*;
import com.pdd.pop.sdk.http.api.pop.response.*;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import io.lettuce.core.internal.LettuceLists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PddPlatformManagerServiceImpl implements PlatformManagerService {

    @Value("${pdd.clientId:123}")
    private String appKey;

    @Value("${pdd.clientSecret:123}")
    private String clientSecret;

    @Autowired
    private PlatformDao platformDao;

    private PopHttpClient popHttpClient;

    @Autowired
    public PddPlatformManagerServiceImpl(PopHttpClient popHttpClient) {
        this.popHttpClient = popHttpClient;
    }

    public PddPlatformManagerServiceImpl() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public String releaseProduct() {
        return null;
    }

    @Override
    public List<LogisticsTemplateVo> getLogisticsTemplate(LogisticsTemplateDto logisticsTemplateDto) {
        String accessToken = logisticsTemplateDto.getAccessToken();

        PddGoodsLogisticsTemplateGetRequest request = new PddGoodsLogisticsTemplateGetRequest();
        request.setPage(logisticsTemplateDto.getPage());
        request.setPageSize(logisticsTemplateDto.getPageSize());
        request.setGoodsStatus(0);
        PddGoodsLogisticsTemplateGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        LogisticsTemplateResultVo logisticsTemplateResultVo = new LogisticsTemplateResultVo();
        List<LogisticsTemplateVo> logisticsTemplateVoList = LettuceLists.newList();
        logisticsTemplateResultVo.setTotalCount(response.getGoodsLogisticsTemplateGetResponse().getTotalCount());
        response.getGoodsLogisticsTemplateGetResponse().getLogisticsTemplateList().forEach(logisticsTemplate -> {
            LogisticsTemplateVo logisticsTemplateVo = new LogisticsTemplateVo();
            logisticsTemplateVo.setTemplateId(logisticsTemplate.getTemplateId());
            logisticsTemplateVo.setTemplateName(logisticsTemplate.getTemplateName());
            logisticsTemplateVo.setCostType(logisticsTemplate.getCostType());
            logisticsTemplateVo.setLastUpdateTime(logisticsTemplate.getLastUpdatedTime());
            logisticsTemplateVoList.add(logisticsTemplateVo);
        });
        return logisticsTemplateVoList;
    }

    @Override
    public MallInfoVo getMallInfo(TokenCreateDto tokenCreateDto) {
        MallInfoVo mallInfoVo = new MallInfoVo();
        String accessToken = tokenCreateDto.getAccessToken();
        log.info("获取到的accessToken={}", accessToken);

        PddMallInfoGetRequest request = new PddMallInfoGetRequest();
        PddMallInfoGetResponse response = null;

        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            log.error("根据accessToken获取店铺信息异常={}", e.getMessage(), e);
            return mallInfoVo; // 返回默认值或抛出业务异常
        }

        if (response == null) {
            log.error("获取店铺信息失败，response为null");
            return mallInfoVo; // 返回默认值或抛出业务异常
        }

        if (response.getErrorResponse() != null && response.getErrorResponse().getErrorCode() != null) {
            log.error("根据accessToken获取店铺信息错误：errorCode={}, errorMsg={}",
                    response.getErrorResponse().getErrorCode(),
                    response.getErrorResponse().getErrorMsg());
        } else {
            log.info("获取到的pdd返回结果={}, 返回的店铺信息={}",
                    JsonUtil.transferToJson(response),
                    response.getMallInfoGetResponse());

            // 使用 BeanUtils 简化属性拷贝
            mallInfoVo.setShopName(response.getMallInfoGetResponse().getMallName());
            mallInfoVo.setShopMallCharacter(response.getMallInfoGetResponse().getMallCharacter());
            mallInfoVo.setShopId(response.getMallInfoGetResponse().getMallId());
            mallInfoVo.setShopLogo(response.getMallInfoGetResponse().getLogo());
            mallInfoVo.setShopMerchantType(response.getMallInfoGetResponse().getMerchantType());
        }
        return mallInfoVo;
    }

    @Override
    public String getGoodsCats() {
        // 获取当前授权商家可发布的商品类目信息
        List<PddGoodsCatsGetResponse.GoodsCatsGetResponseGoodsCatsListItem> goodsCatsGetResponseGoodsCatsListItems = getCatsList(0L);
        return null;
    }

    @Override
    public String getGoodsRule() {
        String accessToken = "your accessToken";
        PddGoodsCatRuleGetRequest request = new PddGoodsCatRuleGetRequest();
        request.setCatId(123L);
        request.setGoodsId(123123L);
        PddGoodsCatRuleGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(JsonUtil.transferToJson(response));
        return "";
    }

    @Override
    public String getCurrentCommodityCategory(String accessToken) {
        // 获取商品类目信息
        PddGoodsAuthorizationCatsRequest request = new PddGoodsAuthorizationCatsRequest();
        request.setParentCatId(0L);
        PddGoodsAuthorizationCatsResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
            if (response.getErrorResponse() != null) {
                log.info("/***************获取商品类目信息错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
                log.info("/***************获取商品类目信息错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
                throw new RuntimeException();
            }
        } catch (Exception e) {
            log.info("/***************获取当前授权商家可发布的商品类目信息错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            throw new RuntimeException(e);
        }
        List<PddGoodsAuthorizationCatsResponse.GoodsAuthCatsGetResponseGoodsCatsListItem> goodsCatsList = response.getGoodsAuthCatsGetResponse().getGoodsCatsList();

        // 转vo方便递归 获取三四级类目
        List<PddGoodsGoodsCatsVO> collect = goodsCatsList.stream()
                .map(map -> JSON.parseObject(JSON.toJSONString(map), PddGoodsGoodsCatsVO.class))
                .collect(Collectors.toList());

        // 循环调用接口获取二级类目
        for (PddGoodsGoodsCatsVO goodsCatsVO : collect) {
            Boolean leaf = goodsCatsVO.getLeaf();

            // 不是叶子类目继续往下查
            if (!leaf) {
                if (goodsCatsVO.getCatId() == 2933) {
                    List<PddGoodsGoodsCatsVO> child = this.getChild(goodsCatsVO.getCatId(), accessToken);
                    goodsCatsVO.setGoodsCatsList(child);
                }
            }
        }
        String toJson = new Gson().toJson(collect);
        log.info("商品类目信息:" + toJson);
        return toJson;
    }

    private List<PddGoodsGoodsCatsVO> getChild(Long id, String accessToken) {
        List<PddGoodsGoodsCatsVO> childList = new ArrayList<>();
        // 获取商品类目信息
        PddGoodsAuthorizationCatsRequest request = new PddGoodsAuthorizationCatsRequest();
        request.setParentCatId(id);
        PddGoodsAuthorizationCatsResponse response = new PddGoodsAuthorizationCatsResponse();
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            log.info("/***************获取当前授权商家可发布的商品类目信息错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取商品类目信息错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取商品类目信息错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        List<PddGoodsAuthorizationCatsResponse.GoodsAuthCatsGetResponseGoodsCatsListItem> list = response.getGoodsAuthCatsGetResponse().getGoodsCatsList();

        for (PddGoodsAuthorizationCatsResponse.GoodsAuthCatsGetResponseGoodsCatsListItem vo : list) {
            PddGoodsGoodsCatsVO catsGetResponseGoodsCatsVO = new PddGoodsGoodsCatsVO();
            catsGetResponseGoodsCatsVO.setCatId(vo.getCatId());
            catsGetResponseGoodsCatsVO.setCatName(vo.getCatName());
            catsGetResponseGoodsCatsVO.setLeaf(vo.getLeaf());
            childList.add(catsGetResponseGoodsCatsVO);
        }
        for (PddGoodsGoodsCatsVO goodsCatsVO : childList) {
            if (goodsCatsVO.getCatId() == 2946 || goodsCatsVO.getCatId() == 3045) {
                // 递归调用获取三级四级类目
                Boolean leaf = goodsCatsVO.getLeaf();
                if (leaf) {
                    return childList;
                }
                List<PddGoodsGoodsCatsVO> child = getChild(goodsCatsVO.getCatId(), accessToken);
                goodsCatsVO.setGoodsCatsList(child);
            }
        }
        return childList;
    }


    @Override
    public String searchPddBrand(String value, Long catId, Long refPid, String accessToken) {
        // 查询品牌
        PddGoodsTemplatePropertyValueSearchRequest request = new PddGoodsTemplatePropertyValueSearchRequest();
        request.setCatId(catId);
        request.setPageNum(1);
        request.setPageSize(30);
        request.setValue(value);
        request.setRefPid(refPid);
        PddGoodsTemplatePropertyValueSearchResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取查询品牌错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取查询品牌错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        List<PddGoodsTemplatePropertyValueSearchResponse.GoodsTemplatePropValSearchResponseListItem> list = response.getGoodsTemplatePropValSearchResponse().getList();
        String toJson = new Gson().toJson(list);
        log.info("品牌信息:" + toJson);
        return toJson;
    }

    @Override
    public String getFreightTemplateData(String accessToken) {
        // 查询运费模板
        PddGoodsLogisticsTemplateGetRequest request = new PddGoodsLogisticsTemplateGetRequest();
        request.setPage(1);
        request.setPageSize(30);
        PddGoodsLogisticsTemplateGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取查询运费模板错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取查询运费模板错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        List<PddGoodsLogisticsTemplateGetResponse.GoodsLogisticsTemplateGetResponseLogisticsTemplateListItem> list = response.getGoodsLogisticsTemplateGetResponse().getLogisticsTemplateList();
        String toJson = new Gson().toJson(list);
        log.info("查询运费模板:" + toJson);
        return toJson;
    }

    @Override
    public String getVideoData(String accessToken) {
        // 关联视频
        PddGoodsFileInfoGetRequest request = new PddGoodsFileInfoGetRequest();
        PddGoodsFileInfoGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取关联视频错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取关联视频错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        List<PddGoodsFileInfoGetResponse.GoodsFileInfoResponseListItem> list = response.getGoodsFileInfoResponse().getList();
        String toJson = new Gson().toJson(list);
        log.info("关联视频:" + toJson);
        return toJson;
    }

    @Override
    public String getCurrentGoodsInfo(Long catId, String accessToken) {
        // 获取商品属性
        PddGoodsCatRuleGetRequest request = new PddGoodsCatRuleGetRequest();
        request.setCatId(catId);
        PddGoodsCatRuleGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取商品属性错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取商品属性错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        List<PddGoodsCatRuleGetResponse.CatRuleGetResponseGoodsPropertiesRulePropertiesItem> properties = response.getCatRuleGetResponse().getGoodsPropertiesRule().getProperties();
        String toJson = new Gson().toJson(properties);
        log.info("商品属性:" + toJson);
        return toJson;
    }

    @Override
    public String getTwoPiecesDiscountRule(Long catId, String accessToken) {
        // 获取商品两件折扣属性
        PddGoodsCatRuleGetRequest request = new PddGoodsCatRuleGetRequest();
        request.setCatId(catId);
        PddGoodsCatRuleGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取商品两件折扣属性错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取商品两件折扣属性错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        PddGoodsCatRuleGetResponse.CatRuleGetResponseTwoPiecesDiscountRule twoPiecesDiscountRule = response.getCatRuleGetResponse().getTwoPiecesDiscountRule();
        String toJson = new Gson().toJson(twoPiecesDiscountRule);
        log.info("商品属性:" + toJson);
        return toJson;
    }

    @Override
    public String getGoodsSpecifications(Long catId, String accessToken) {
        // 获取商品规格
        PddGoodsSpecGetRequest request = new PddGoodsSpecGetRequest();
        request.setCatId(catId);
        PddGoodsSpecGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取商品规格错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取商品规格错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        List<PddGoodsSpecGetResponse.GoodsSpecGetResponseGoodsSpecListItem> list = response.getGoodsSpecGetResponse().getGoodsSpecList();
        String toJson = new Gson().toJson(list);
        log.info("商品规格:" + toJson);
        return toJson;
    }

    @Override
    public String getCustomSpecifications(Long parentSpecId, String specName, String accessToken) {
        // 自定义规格
        PddGoodsSpecIdGetRequest request = new PddGoodsSpecIdGetRequest();
        request.setParentSpecId(parentSpecId);
        request.setSpecName(specName);
        PddGoodsSpecIdGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取自定义规格错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取自定义规格错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        PddGoodsSpecIdGetResponse.GoodsSpecIdGetResponse getResponse = response.getGoodsSpecIdGetResponse();
        String toJson = new Gson().toJson(getResponse);
        log.info("自定义规格:" + toJson);
        return toJson;
    }

    @Override
    public String getGoodsCountry(String accessToken) {
        // 商品地区/国家接口
        PddGoodsCountryGetRequest request = new PddGoodsCountryGetRequest();
        PddGoodsCountryGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String toJson = new Gson().toJson(response.getGoodsCountryGetResponse().getCountryList());
        log.info("商品地区/国家接口:" + toJson);
        return toJson;
    }

    @Override
    public String goodsImgUpload(String fileUrl, String accessToken) {
        // 商品图片上传接口
        PddGoodsImgUploadRequest request = new PddGoodsImgUploadRequest();
        request.setFile(fileUrl);
        PddGoodsImgUploadResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (response.getErrorResponse() != null) {
            log.info("/***************获取商品图片上传错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            log.info("/***************获取商品图片上传错误码：" + response.getErrorResponse().getErrorCode() + "**************/");
            throw new RuntimeException();
        }
        return response.getGoodsImgUploadResponse().getUrl();
    }

    @Override
    public String filesPaceImgUpload(String fileUrl, String accessToken) {
        // 图片上传到图片空间
        PddGoodsFilespaceImageUploadRequest request = new PddGoodsFilespaceImageUploadRequest();
        request.setFile(fileUrl);
        PddGoodsFilespaceImageUploadResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("图片上传到图片空间错误!");
        }
        return new Gson().toJson(response);
    }

    @Override
    public Map<String, Object> releaseGoods(PddProductPropertyDto pddProductPropertyDto, String accessToken) {
        Map<String, Object> resultMap = new HashMap<>();

        PddGoodsAddRequest request = new PddGoodsAddRequest();

        // 商品轮播图
        request.setCarouselGallery(pddProductPropertyDto.getCommon().getCarouselGallery());

        // 叶子类目ID
        request.setCatId(pddProductPropertyDto.getCommon().getCatId());

        // 物流运费模板ID (内地包邮默认模板)
        request.setCostTemplateId(pddProductPropertyDto.getCommon().getCostTemplateId());
        // 地区/国家ID
        request.setCountryId(0);

        // 团购人数
        request.setCustomerNum(2L);

        // 商品详情图
        request.setDetailGallery(pddProductPropertyDto.getCommon().getDetailGallery());

        // 商品描述 字数限制：20-500
        request.setGoodsDesc(pddProductPropertyDto.getCommon().getDetails());

        // 商品标题
        request.setGoodsName(pddProductPropertyDto.getCommon().getGoodsName());

        // 商品sku外部编码
        request.setOutGoodsId(pddProductPropertyDto.getCommon().getOuterId());


        // 商品属性
        try {
            List<GoodsPropertiesItem> goodsProperties = new ArrayList<>();
            // 款式
            PddGoodsPropertiesDto ks = pddProductPropertyDto.getPddSJKKS();
            if(null != ks){
                GoodsPropertiesItem itemKS = new GoodsPropertiesItem();
                // 引用属性id
                itemKS.setRefPid(ks.getRefPid());
                // 属性值
                itemKS.setValue(ks.getValue());
                // 属性单位
                for (String s : ks.getValueUnit()) {
                    itemKS.setValueUnit(s);
                }
                // 属性值id
                itemKS.setVid(ks.getVid());
                goodsProperties.add(itemKS);
            }

            // 风格
            PddGoodsPropertiesDto fg = pddProductPropertyDto.getPddSJKFG();
            if(null != fg){
                GoodsPropertiesItem itemFG = new GoodsPropertiesItem();
                // 引用属性id
                itemFG.setRefPid(fg.getRefPid());
                // 属性值
                itemFG.setValue(fg.getValue());
                // 属性单位
                for (String s : fg.getValueUnit()) {
                    itemFG.setValueUnit(s);
                }
                // 属性值id
                itemFG.setVid(fg.getVid());
                goodsProperties.add(itemFG);
            }

            // 保护套质地
            PddGoodsPropertiesDto bhtzd = pddProductPropertyDto.getPddSJKBHTZD();
            if(null != bhtzd){
                GoodsPropertiesItem itemBHTZD = new GoodsPropertiesItem();
                // 引用属性id
                itemBHTZD.setRefPid(bhtzd.getRefPid());
                // 属性值
                itemBHTZD.setValue(bhtzd.getValue());
                // 属性单位
                for (String s : bhtzd.getValueUnit()) {
                    itemBHTZD.setValueUnit(s);
                }
                // 属性值id
                itemBHTZD.setVid(bhtzd.getVid());
                goodsProperties.add(itemBHTZD);
            }

            // 流行元素
            List<PddGoodsPropertiesDto> pddSJKLXYS = pddProductPropertyDto.getPddSJKLXYS();
            if(null != pddSJKLXYS && pddSJKLXYS.size() > 0){
                for (PddGoodsPropertiesDto lxys : pddSJKLXYS) {
                    GoodsPropertiesItem itemLXYS = new GoodsPropertiesItem();
                    // 引用属性id
                    itemLXYS.setRefPid(lxys.getRefPid());
                    // 属性值
                    itemLXYS.setValue(lxys.getValue());
                    // 属性单位
                    for (String s : lxys.getValueUnit()) {
                        itemLXYS.setValueUnit(s);
                    }
                    // 属性值id
                    itemLXYS.setVid(lxys.getVid());
                    goodsProperties.add(itemLXYS);
                }
            }
            request.setGoodsProperties(goodsProperties);
        } catch (Exception e) {
            log.error("商品属性错误");
            resultMap.put("false", "商品属性错误");
            return resultMap;
        }


        // 1-国内普通商品，2-一般贸易，3-保税仓BBC直供，4-海外BC直邮 ,5-流量 ,6-话费 ,7-优惠券 ,8-QQ充值 ,9-加油卡，15-商家卡券，18-海外CC行邮 19-平台卡券
        request.setGoodsType(1);

        // 是否支持假一赔十，false-不支持，true-支持
        request.setIsFolt(pddProductPropertyDto.isPddJYPS());

        // 是否获取商品发布警告信息，默认为忽略
        request.setIgnoreEditWarn(true);

        // 是否预售
        request.setIsPreSale(false);

        // 是否7天无理由退换货，true-支持，false-不支持
        request.setIsRefundable(true);

        // 参考价格
        request.setMarketPrice(2500L);

        // 是否二手商品，true -二手商品 ，false-全新商品
        request.setSecondHand(false);

        // 默认24小时发货
        request.setShipmentLimitSecond(86400L);
        if ("2".equals(pddProductPropertyDto.getPddShipmentsAging())) {
            request.setShipmentLimitSecond(172800L);
        }

        List<SkuListItem> skuList = new ArrayList<>();

        List<PddDataUploadImageDto> pddDataUploadImageDto = pddProductPropertyDto.getDataUploadImageVO();
        for (PddDataUploadImageDto dataUploadImageDto : pddDataUploadImageDto) {
            SkuListItem item3 = new SkuListItem();

            // 前端传的上架方式 0-直接上架 1-放入仓库 =============== 拼多多的sku上架状态，0-已下架，1-上架中
            String shelfProcessing = pddProductPropertyDto.getCommon().getShelfProcessing();
            item3.setIsOnsale(shelfProcessing.equals("0") ? 1 : 0);
            item3.setLimitQuantity(999L);


            // 商品团购价格=价格-单卖价高于拼团价多少元
            try {
                String price = pddProductPropertyDto.getCommon().getPrice();
                String pddPriceAbo = pddProductPropertyDto.getPddPriceAbo();
                BigDecimal sub = new BigDecimal(price).subtract(new BigDecimal(pddPriceAbo));
                BigDecimal multiply = sub.multiply(new BigDecimal(100));
                item3.setMultiPrice(multiply.longValue());
                // item3.setMultiPrice(2000L);

                // 商品单买价格
                BigDecimal mulPrice = new BigDecimal(price).multiply(new BigDecimal(100));
                item3.setPrice(mulPrice.longValue());
            } catch (Exception e) {
                log.error("商品价格错误");
                resultMap.put("false", "商品价格错误");
                return resultMap;
            }

            // 商品sku库存初始数量，后续库存update只使用stocks.update接口进行调用
            item3.setQuantity(Long.parseLong(pddProductPropertyDto.getCommon().getQuantity()));

            List<SkuListItemSkuPropertiesItem> skuProperties = new ArrayList<>();

            // SKU属性
            SkuListItemSkuPropertiesItem item4 = new SkuListItemSkuPropertiesItem();
            skuProperties.add(item4);

            // 页面传过来的规格
            PddGoodsPropertiesDto specName1 = pddProductPropertyDto.getSpecName1();
            PddGoodsPropertiesDto specName2 = pddProductPropertyDto.getSpecName2();

            // 默认规格1为型号 规格2为款式
            Long specId1 = 1473L;
            Long specId2 = 1218L;

            String model = this.getCustomSpecifications(null == specName1 || 0L ==  specName1.getVid() ? specId1 : specName1.getVid(), dataUploadImageDto.getProductName(), accessToken);
            String style = this.getCustomSpecifications(null == specName2 || 0L ==  specName2.getVid() ? specId2 : specName2.getVid(), dataUploadImageDto.getSpecName(), accessToken);
            Long modelSpecId = (Long) JSON.parseObject(model, Map.class).get("specId");
            Long styleSpecId = (Long) JSON.parseObject(style, Map.class).get("specId");

            String spec = "["+styleSpecId+","+modelSpecId+"]";
            item3.setSpecIdList(spec);
            String imgUpload = this.goodsImgUpload(dataUploadImageDto.getLocalPath(), accessToken);
            item3.setThumbUrl(imgUpload);
            item3.setWeight(0L);
            item3.setSkuProperties(skuProperties);
            skuList.add(item3);
        }
        request.setSkuList(skuList);

        request.setTwoPiecesDiscount(Integer.parseInt(pddProductPropertyDto.getPddLJZK()));
        PddGoodsAddResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            log.error("发布商品失败" + response.getErrorResponse());
            resultMap.put("false", response.getErrorResponse());
            return resultMap;

        }
        if(null != response.getErrorResponse()){
            String toJson = new Gson().toJson(response.getErrorResponse());
            resultMap.put("false", toJson);
            return resultMap;
        }
        String toJson = new Gson().toJson(response.getGoodsAddResponse());
        resultMap.put("true", toJson);
        log.info("新增商品成功");
        return resultMap;
    }

    @Override
    public String getPageCode(JSONObject jsonObject) {
        String clientId = "your clientId";
        String clientSecret = "your clientSecret";

        PddCloudIsvPageCodeRequest request = new PddCloudIsvPageCodeRequest();
        request.setHttpReferer("http://dadan.com/sendOrder");
        List<String> mallIdList = new ArrayList<String>();
        mallIdList.add("1");
        request.setMallIdList(mallIdList);
        request.setUserId("1");
        PddCloudIsvPageCodeResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response.getResponse().getPageCode();
    }


    private List<PddGoodsCatsGetResponse.GoodsCatsGetResponseGoodsCatsListItem> getCatsList(Long currentId) {
        String accessToken = "ef817b4398574eb3b674999cd30c51b850ed26d3";
        PddGoodsCatsGetRequest request = new PddGoodsCatsGetRequest();
        request.setParentCatId(currentId);
        PddGoodsCatsGetResponse response = null;
        try {
            response = popHttpClient.syncInvoke(request, accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getGoodsCatsGetResponse().getGoodsCatsList().stream().forEach(goods -> {
            if (!goods.getCatName().equals("手机壳")) {
                getCatsList(goods.getCatId());
            }
        });
        return response.getGoodsCatsGetResponse().getGoodsCatsList();
    }

    @Override
    public String getAuthUrl(TokenCreateDto tokenCreateDto) {
        PlatformEntity platform = platformDao.getPlatformById(tokenCreateDto.getPlatformId());
        return platform.getServerUrl() + URLEncoder.encode(platform.getAuthUrl() + appKey + "&redirect_uri=" + platform.getRedirectUrl() + "&state=" + tokenCreateDto.getShopType() + "&platformId=" + tokenCreateDto.getPlatformId());
    }

    @Override
    public TokenCreateVo getAccessToken(TokenCreateDto tokenCreateDto) {
        TokenCreateVo tokenCreateVo = new TokenCreateVo();
        PlatformEntity platform = platformDao.getPlatformById(EnumShopType.PDD.getIndex());
        String appKey = platform.getAppKey();
        String appSecret = platform.getAppSecret();
        PopAccessTokenClient accessTokenClient = new PopAccessTokenClient(appKey, appSecret);
        // 生成AccessToken
        try {
            AccessTokenResponse response = accessTokenClient.generate(tokenCreateDto.getCode());
            if (response.getErrorResponse() != null) {
                log.info("/***************获取拼多多授权token错误：" + response.getErrorResponse().getErrorMsg() + "**************/");
            } else {
                tokenCreateVo.setAccessToken(response.getAccessToken());
                tokenCreateVo.setExpiresIn(response.getExpiresIn());
                tokenCreateVo.setRefreshToken(response.getRefreshToken());
                tokenCreateVo.setScope(response.getScope());
                tokenCreateVo.setOwnerId(response.getOwnerId());
                tokenCreateVo.setOwnerName(response.getOwnerName());
            }
        } catch (Exception e) {
            log.error("获取拼多多token授权异常={}", e.getMessage(), e);
        }
        return tokenCreateVo;
    }
}
